package util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * User: key
 * ClassName:DbUtils
 * Date: 2023/5/5
 * Time: 18:51
 * description:
 */
public class DbUtils {
    private static final ThreadLocal<Connection> T = new ThreadLocal<>();
    private static DruidDataSource ds;
    static {
        Properties pro = new Properties();
        try {
            pro.load(DbUtils.class.getResourceAsStream("/jdbc.properties"));
            //创建数据源
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
        Connection con = T.get();
        try {
            if(con == null){
                con = ds.getConnection();
                T.set(con);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
    public static DataSource getDataSource(){
        return ds;
    }
    public static void closeAll(ResultSet rs, PreparedStatement ps,Connection con){
        try {
            if(rs != null)rs.close();
            if(ps != null)ps.close();
            if(con != null){
                con.close();
                T.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void begin(){
        Connection con = getConnection();
        try {
            con.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void commit(){
        Connection con = getConnection();
        try {
            con.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        closeAll(null,null,con);
    }
    public static void rollback(){
        Connection con = getConnection();
        try {
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        closeAll(null,null,con);
    }
}
